package com.google.android.mypetrol;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.util.Log;

public class Provider extends ContentProvider {
	
	private static final String sDatabaseName = "mypetrol.db";
	private static final int DATABASE_VERSION = 1;
	
	public static final Uri CONTENT_URI = Uri.parse( "content://mypetrol");
	
	private DatabaseHelper mOpenHelper;
	public Provider() {
	}

	private static class DatabaseHelper extends SQLiteOpenHelper {
		public DatabaseHelper(Context context) {
			super(context, sDatabaseName, null, DATABASE_VERSION);
		}
		
		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL("CREATE TABLE petrol (" + "_id INTEGER PRIMARY KEY,"
					+ "datetime datetime,"+ "total INTEGER," + "price FLOAT, " 
					+ "year String," + "month String," + "date String)");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			db.execSQL("DROP TABLE IF EXISTS petrol");
			onCreate(db);
		}
	}

	@Override
	public boolean onCreate() {
		mOpenHelper = new DatabaseHelper(getContext());
		return true;
	}

	@Override
	public int delete(Uri arg0, String arg1, String[] arg2) {
		SQLiteDatabase db =  mOpenHelper.getWritableDatabase();
		db.delete("petrol", arg1, arg2);
		return 0;
	}

	@Override
	public String getType(Uri arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Uri insert(Uri url, ContentValues values) {
		Log.d("db", "insert");
		SQLiteDatabase db =  mOpenHelper.getWritableDatabase();
		long rowId = db.insert("petrol", "date", values);
		Uri uri = null;
		if (rowId > 0) {
			uri = Uri.parse(
					"content://mypetrol/petrol/" + rowId);
		} 
		return uri;
	}


	@Override
	public Cursor query(Uri arg0, String[] columns, String selection, String[] selectionArgs,
			String sortOrder) {
		SQLiteDatabase db =  mOpenHelper.getReadableDatabase();
		return db.query("petrol", columns, selection, selectionArgs, null, null, sortOrder);
	}

	@Override
	public int update(Uri arg0, ContentValues values, String whereClause, String[] whereArgs) {
		SQLiteDatabase db =  mOpenHelper.getWritableDatabase();
		return db.update("petrol", values, whereClause, whereArgs);
	}

}
